package com.sskj.fabi.ui.fragment;


import android.support.design.widget.BottomSheetDialog;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.shizhefei.mvc.MVCCoolHelper;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.util.ToastUtil;
import com.sskj.fabi.R;
import com.sskj.fabi.R2;
import com.sskj.fabi.bean.BuySellBean;
import com.sskj.fabi.bean.OrderDetailBean;
import com.sskj.fabi.component.DaggerUserDataComponent;
import com.sskj.fabi.presenter.BuySellFragmentPresenter;
import com.sskj.fabi.util.TipFabiUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.FabiBuySellEnum;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.mvchelper.ModelRx2DataSource;
import com.sskj.lib.util.AppCircleCheckUtil;
import com.sskj.lib.util.AppDirectCheckUtil;
import com.sskj.lib.util.CoinUtil;
import com.sskj.lib.util.StringUtil;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

@Route(path = RConfig.FABI_FRAGMENT_BUY_SELL)
public class BuySellFragment extends BaseFragment<BuySellFragmentPresenter> {
    @Autowired
    boolean isBuy;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.coolRefreshView)
    CoolRefreshView coolRefreshView;

    @Inject
    UserViewModel userViewModel;
    private UserData userData;
    private SlimAdapter slimAdapter;
    private int curPos;
    private BottomSheetDialog orderSheet;
    private MVCCoolHelper<List<BuySellBean>> mvcHelper;

    @Override
    protected int getLayoutId() {
        return R.layout.fabi_fragment_buy_sell;
    }

    @Override
    public BuySellFragmentPresenter getPresenter() {
        return new BuySellFragmentPresenter();
    }

    @Override
    protected void initView() {
        ARouter.getInstance().inject(this);
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(getActivity())
                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 20))
                .setDividerColor(ContextCompat.getColor(App.INSTANCE, R.color.transparent))
        );
        // 剩余数量
        slimAdapter = SlimAdapter.create().register(R.layout.fabi_recy_item_buy_sell, new SlimInjector<BuySellBean>() {
            @Override
            public void onInject(BuySellBean data, IViewInjector injector, List payloads) {
                injector.clicked(R.id.btSale, v -> {
                    curPos = slimAdapter.getData().indexOf(data);
                    trade();
                }).text(R.id.tvName, data.getRealname())
                        .text(R.id.tvDealNum, String.format(App.INSTANCE.getString(R.string.fabi_buySellFragment1_h), CoinUtil.keepUSDT(data.getCd_num())))
                        .text(R.id.tvPercent, String.format(App.INSTANCE.getString(R.string.fabi_buySellFragment2_h), data.getRate()))
                        .text(R.id.tvNum, data.getAmount())  // 剩余数量
                        .text(R.id.tvLimitMoney, data.getLimitNum())
                        .text(R.id.tv_china_money, data.getPrice())
                        .text(R.id.tvPhoto, StringUtil.getFirstName(data.getRealname()))
                        .text(R.id.btSale, isBuy ? FabiBuySellEnum.BUY.getTitle() : FabiBuySellEnum.SELL.getTitle())
                        .visibility(R.id.iv_wechat, "1".equals(data.getPay_wx()) ? View.VISIBLE : View.GONE)
                        .visibility(R.id.iv_bank, "1".equals(data.getPay_backcard()) ? View.VISIBLE : View.GONE)
                        .visibility(R.id.iv_alipay, "1".equals(data.getPay_alipay()) ? View.VISIBLE : View.GONE)
                ;
            }
        });
        slimAdapter.attachTo(recyclerView).updateData(new ArrayList());
        ModelRx2DataSource<BuySellBean> dataSource = new ModelRx2DataSource<>((ModelRx2DataSource.OnLoadSource<BuySellBean>)
                page -> mPresenter.getData(page + "", 20 + "", isBuy), 20);
        mvcHelper = new MVCCoolHelper<>(coolRefreshView);
        mvcHelper.setDataSource(dataSource);
        mvcHelper.setAdapter(slimAdapter);
        mvcHelper.refresh();
    }

    private void trade() {
        if (!AppDirectCheckUtil.checkLogin(getActivity(), userData)) {
            return;
        }
        BuySellBean dataItem = (BuySellBean) slimAdapter.getDataItem(curPos);
        if (userData.getAccount().equals(dataItem.getAccount())) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.fabi_buySellFragment3_h));
            return;
        }
        if (!isBuy) {
            // TODO: 19-5-6
            if (!AppCircleCheckUtil.checkTradePwd(getActivity(), userData)) {
                return;
            }
        } else {
            if (!AppCircleCheckUtil.checkTradePwd(getActivity(), userData)) {
                return;
            }
        }

        showSell();

    }

    private void showSell() {
        BuySellBean dataItem = (BuySellBean) slimAdapter.getDataItem(curPos);
        orderSheet = TipFabiUtil.showTrade(getActivity(), isBuy,
                dataItem.price,
                dataItem.getMin_price(),
                dataItem.getMax_price(),
                dataItem.getOriginAmount(),
                str -> {
                    mPresenter.order(str[2], dataItem.getOrder_no(), str[0], str[1], isBuy);
                });
        orderSheet.show();
    }

    public void orderSuccess(OrderDetailBean orderDetailBean) {
        if (orderSheet != null && orderSheet.isShowing()) {
            orderSheet.dismiss();
        }
        if (mvcHelper != null) {
            mvcHelper.refresh();
        }
        ARouter.getInstance().build(RConfig.FABI_ORDER_RECORD_DETAIL)
                .withString(Constans.ORDER_NUM, orderDetailBean.getDealEntrustNo())
                .withBoolean(Constans.IS_BUYER, isBuy)
                .navigation();

    }
}

